import datetime
import hashlib
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
import uuid

# 自定义用户模型
class User(models.Model):
    username = models.CharField(max_length=64, unique=True)
    password_hash = models.CharField(max_length=128)  # 存储密码的哈希值
    session_token = models.CharField(max_length=64, blank=True)
    is_admin = models.BooleanField(default=False)
    description = models.TextField(blank=True,max_length=10000)
    is_banned = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    avatar=models.IntegerField(default=0)
    topimage=models.IntegerField(default=0)

    def set_password(self, raw_password):
        """生成密码哈希"""
        self.password_hash = hashlib.sha256(raw_password.encode()).hexdigest()
    
    def check_password(self, raw_password):
        """验证密码"""
        return self.password_hash == hashlib.sha256(raw_password.encode()).hexdigest()
    
    def generate_session_token(self):
        """生成会话令牌"""
        self.session_token = uuid.uuid4().hex
        self.save()
        return self.session_token
    
    
    def clear_session_token(self):
        """清除会话令牌"""
        self.session_token = ""
        self.save()
    @property
    def password(self):
        """兼容Django密码字段的只读属性"""
        return self.password_hash
# 图片模型
class Image(models.Model):
    display = models.BooleanField(default=False)  # 是否显示
    uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    date = models.DateTimeField(auto_now_add=True)
    description = models.TextField(blank=True)
    title = models.CharField(max_length=200, blank=True,default="Untitled")
    image_file = models.ImageField(upload_to='images/')
    
    def __str__(self):
        return self.title or f"Image-{self.id}"
# 标签模型
class Tag(models.Model):
    TAG_TYPES = [
        ('BOOL', '布尔值'),
        ('INT', '整数'),
        ('STR', '字符串'),
        ('FLOAT', '浮点数'),
        ('DATE', '日期'),
    ]
    
    name = models.CharField(max_length=100, unique=True)
    tag_type = models.CharField(max_length=10, choices=TAG_TYPES,default="STR")
    description = models.TextField(blank=True)

    def __str__(self):
        return f"{self.name} ({self.get_tag_type_display()})"
from django.utils import timezone
def get_bool(s:str):
    if isinstance(s,str)==False:
        return s
    BOOL=['True','true','1','TRUE','yes','ok','YES','Yes','Ok','OK']
    return True if s in BOOL else False
class ImageTag(models.Model):
    image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='tags')
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
    
    # 所有可能的值字段
    bool_value = models.BooleanField(null=True, blank=True)
    int_value = models.IntegerField(null=True, blank=True)
    str_value = models.CharField(max_length=255, null=True, blank=True)
    float_value = models.FloatField(null=True, blank=True)
    date_value=models.DateField(null=True,blank=True)
    
    class Meta:
        unique_together = ('image', 'tag')
        indexes = [
            models.Index(fields=['tag']),
            models.Index(fields=['int_value']),
            models.Index(fields=['str_value']),
        ]
    
    def get_value(self):
        """根据标签类型返回正确的值"""
        if self.tag.tag_type == 'BOOL':
            return self.bool_value
        elif self.tag.tag_type == 'INT':
            return self.int_value
        elif self.tag.tag_type == 'STR':
            return self.str_value
        elif self.tag.tag_type == 'FLOAT':
            return self.float_value
        elif self.tag.tag_type == 'DATE':
            return self.date_value
        return None
    
    def set_value(self, value):
        """根据标签类型设置正确的值字段"""
        if self.tag.tag_type == 'BOOL':
            self.bool_value = get_bool(value)
        elif self.tag.tag_type == 'INT':
            self.int_value = int(value)
        elif self.tag.tag_type == 'STR':
            self.str_value = str(value)
        elif self.tag.tag_type == 'FLOAT':
            self.float_value = float(value)
        elif self.tag.tag_type == 'DATE':
            self.date_value=timezone.make_aware(datetime.datetime.strptime(value, '%Y-%m-%d')).date()
